package MEET.src.View;

import MEET.src.code.Meeting;
import MEET.src.code.MeetingDao;

import javax.swing.Timer;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;


public class Conference extends JFrame {
    private final MeetingService1 meetingService1;
    private DefaultTableModel meetingTableModel;
    private JTable meetingTable;

    public Conference() {
        meetingService1 = new MeetingService1();
        meetingTableModel = new DefaultTableModel(
                new String[]{"会议ID","会议名称","主持人","开始时间","结束时间","会议室","会议形式","会议类型","审核状态"},
                0
        );
        initUI();
        refreshMeetingList();
    }


    private void initUI() {
        setTitle("上海电力大学会议室预订系统");
        setSize(1200, 800);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); // 设置关闭操作为隐藏窗口
        setLocationRelativeTo(null);

        // 初始化表格模型
        meetingTableModel = new DefaultTableModel(
                new String[]{"会议ID","会议名称","主持人","开始时间","结束时间","会议室","会议形式","会议类型","审核状态"},
                0
        );

        // 创建表格
        meetingTable = new JTable(meetingTableModel) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        meetingTable.setForeground(new Color(60, 60, 60)); // 深灰色
        meetingTable.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));

        // 设置表格样式
        meetingTable.setRowHeight(35);
        meetingTable.setShowGrid(false);
        meetingTable.setSelectionBackground(new Color(197, 202, 233));
        meetingTable.setIntercellSpacing(new Dimension(0, 0));
        meetingTable.setFillsViewportHeight(true);

        // 设置表头样式
        JTableHeader header = meetingTable.getTableHeader();
        header.setFont(new Font("Microsoft YaHei", Font.BOLD, 12));
        header.setBackground(new Color(70, 130, 180));
        header.setForeground(Color.WHITE);
        header.setPreferredSize(new Dimension(header.getWidth(), 35));

        // 设置状态列渲染器
        meetingTable.getColumnModel().getColumn(8).setCellRenderer(new StatusCellRenderer());

        // 设置时间列居中
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        meetingTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
        meetingTable.getColumnModel().getColumn(4).setCellRenderer(centerRenderer);

        // 添加到滚动面板
        JScrollPane scrollPane = new JScrollPane(meetingTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());

        // 设置主界面布局
        JPanel mainPanel = new JPanel(new BorderLayout());
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);

        JButton refreshBtn = new JButton("刷新");
        refreshBtn.addActionListener(e -> refreshMeetingList());
        toolBar.add(refreshBtn);

        JButton newReservationBtn = new JButton("新建预订");
        newReservationBtn.addActionListener(e -> openReservationDialog());
        toolBar.add(newReservationBtn);

        mainPanel.add(toolBar, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        setContentPane(mainPanel);
    }

    // 按钮样式统一方法
    private void styleButton(JButton button, Color bgColor) {
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(bgColor.darker(), 1),
                BorderFactory.createEmptyBorder(5, 15, 5, 15)
        ));
        button.setFocusPainted(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));}

    private void openReservationDialog() {
        ReservationDialog dialog = new ReservationDialog(this, meetingService1);
        dialog.setVisible(true);
        dialog.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                refreshMeetingList();
            }
        });
    }

    private String buildLocationString(Meeting meeting) {
        // 实现会议室位置信息的构建逻辑
        return meeting.getLocation() != null ? meeting.getLocation() : "未指定";
    }

    private void refreshMeetingList() {
        // 创建会议室主题加载动画对话框
        JDialog loadingDialog = new JDialog(this, "", Dialog.ModalityType.MODELESS);
        loadingDialog.setUndecorated(true);
        loadingDialog.setSize(300, 200);
        loadingDialog.setLocationRelativeTo(this);

        final long animationStartTime = System.currentTimeMillis();
        final int MIN_DISPLAY_TIME = 1500;
        final int[] seatStatus = {0};
        final int TOTAL_SEATS = 8;
        final int ANIMATION_INTERVAL = 300;
        final boolean[] isComplete = {false};

        // 会议室动画面板
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 绘制会议室背景
                g2.setColor(new Color(240, 240, 240));
                g2.fillRoundRect(50, 30, 200, 100, 20, 20);

                // 绘制会议桌
                g2.setColor(new Color(210, 180, 140));
                g2.fillRoundRect(100, 50, 100, 60, 10, 10);

                // 动态绘制座位
                int[] seatX = {70, 90, 130, 180, 220, 220, 180, 130};
                int[] seatY = {70, 50, 40, 50, 70, 110, 120, 110};

                for (int i = 0; i < TOTAL_SEATS; i++) {
                    if (i < seatStatus[0]) {
                        g2.setColor(isComplete[0] ? new Color(50, 150, 50) : new Color(70, 130, 180));
                    } else {
                        g2.setColor(new Color(220, 220, 220));
                    }
                    g2.fillOval(seatX[i], seatY[i], 20, 20);
                }

                // 加载文字
                g2.setColor(Color.DARK_GRAY);
                g2.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
                String text = isComplete[0] ? "会议室准备就绪!"
                        : "正在准备会议室 (" + seatStatus[0] + "/" + TOTAL_SEATS + ")";
                g2.drawString(text, 80, 160);
            }
        };
        panel.setBackground(Color.WHITE);
        loadingDialog.add(panel);
        loadingDialog.setVisible(true);

        // 开启动画定时器
        Timer timer = new Timer(ANIMATION_INTERVAL, e -> {
            if (seatStatus[0] < TOTAL_SEATS) {
                seatStatus[0]++;
                panel.repaint();
            } else {
                isComplete[0] = true;
                panel.repaint();
                ((Timer)e.getSource()).stop();
            }
        });
        timer.start();

        // 异步加载会议数据
        new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                List<Meeting> meetings = meetingService1.getAllMeetings();
                SwingUtilities.invokeLater(() -> {
                    meetingTableModel.setRowCount(0);
                    if (meetings.isEmpty()) {
                        meetingTableModel.addRow(new Object[]{"", "⚠ 没有会议数据", "", "", "", "", "", "", ""});
                    } else {
                        for (Meeting m : meetings) {
                            meetingTableModel.addRow(new Object[]{
                                    m.getMID(),
                                    m.getMname(),
                                    m.getName(),
                                    new SimpleDateFormat("yyyy-MM-dd HH:mm").format(m.getMstarttime()),
                                    new SimpleDateFormat("yyyy-MM-dd HH:mm").format(m.getMendtime()),
                                    buildLocationString(m),
                                    m.getForm(),
                                    m.getType(),
                                    m.getStatus()
                            });
                        }
                        int lastRow = meetingTableModel.getRowCount() - 1;
                        meetingTable.scrollRectToVisible(meetingTable.getCellRect(lastRow, 0, true));
                        meetingTable.setRowSelectionInterval(lastRow, lastRow);
                    }
                });
                return null;
            }

            @Override
            protected void done() {
                try {
                    long elapsed = System.currentTimeMillis() - animationStartTime;
                    if (elapsed < MIN_DISPLAY_TIME) {
                        Thread.sleep(MIN_DISPLAY_TIME - elapsed);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    isComplete[0] = true;
                    panel.repaint();
                    loadingDialog.dispose();
                    timer.stop();
                }
            }
        }.execute();
    }

    private void updateMeetingTable(List<Meeting> meetings) {
        SwingUtilities.invokeLater(() -> {
            meetingTableModel.setRowCount(0);
            if (meetings.isEmpty()) {
                meetingTableModel.addRow(new Object[]{"", "⚠ 没有会议数据", "", "", "", "", "", "", ""});
            } else {
                for (Meeting m : meetings) {
                    meetingTableModel.addRow(new Object[]{
                            m.getMID(),
                            m.getMname(),
                            m.getName(),
                            new SimpleDateFormat("yyyy-MM-dd HH:mm").format(m.getMstarttime()),
                            new SimpleDateFormat("yyyy-MM-dd HH:mm").format(m.getMendtime()),
                            buildLocationString(m),
                            m.getForm(),
                            m.getType(),
                            m.getStatus()
                    });
                }
                int lastRow = meetingTableModel.getRowCount() - 1;
                meetingTable.scrollRectToVisible(meetingTable.getCellRect(lastRow, 0, true));
                meetingTable.setRowSelectionInterval(lastRow, lastRow);
            }
        });
    }



    private void showErrorDialog(Exception e) {
        SwingUtilities.invokeLater(() ->
                JOptionPane.showMessageDialog(
                        Conference.this,
                        "加载失败: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE));
    }

    // 状态单元格渲染器
    class StatusCellRenderer extends DefaultTableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            if (value instanceof JLabel) {
                return (JLabel)value;
            }

            String status = value != null ? value.toString() : "";
            JLabel label = new JLabel(status);
            label.setOpaque(true);
            label.setHorizontalAlignment(SwingConstants.CENTER);
            label.setFont(new Font("Microsoft YaHei", Font.BOLD, 12));

            switch(status) {
                case "待审核":
                    label.setBackground(new Color(255, 152, 0));
                    break;
                case "已通过":
                    label.setBackground(new Color(76, 175, 80));
                    break;
                case "已拒绝":
                    label.setBackground(new Color(244, 67, 54));
                    break;
                default:
                    label.setBackground(Color.LIGHT_GRAY);
            }

            label.setForeground(Color.WHITE);
            label.setBorder(BorderFactory.createEmptyBorder(3, 10, 3, 10));
            return label;
        }
    }
}

class ReservationDialog extends JDialog {
    private final MeetingService1 meetingService1;
    private JTextField meetingIdField = new JTextField(20);
    private JTextField meetingNameField = new JTextField(20);
    private JTextField hostField = new JTextField(20);
    private JComboBox<String> meetingTypeCombo = new JComboBox<>(
            new String[]{"学术会议", "讲座会议", "教学会议", "学生会议", "党建会议", "培训会议"});
    private JComboBox<String> meetingFormCombo = new JComboBox<>(
            new String[]{"线上会议", "线下会议"});
    private JComboBox<String> auditStatusCombo = new JComboBox<>(
            new String[]{"待审核", "已通过", "已拒绝"});
    private JSpinner startTimeSpinner = new JSpinner(new SpinnerDateModel());
    private JSpinner endTimeSpinner = new JSpinner(new SpinnerDateModel());
    private JComboBox<String> campusCombo = new JComboBox<>(new String[]{"临港", "杨浦"});
    private JComboBox<String> locationCombo = new JComboBox<>();
    private JComboBox<String> roomNumberCombo = new JComboBox<>();
    private JTextField cidField = new JTextField(20);
    private JTextField userIdField = new JTextField(20);

    public ReservationDialog(Frame owner, MeetingService1 service) {
        super(owner, "新建会议预订", true);
        this.meetingService1 = service;
        initUI();
    }

    private void initUI() {
        // 设置对话框整体样式
        setLayout(new GridBagLayout());
        getContentPane().setBackground(new Color(240, 240, 245));
        ((JComponent)getContentPane()).setBorder(
                BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(200, 200, 210)),
                        BorderFactory.createEmptyBorder(15, 15, 15, 15)
                )
        );

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(8, 8, 8, 8);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 初始化所有组件样式
        styleTextField(meetingIdField);
        styleTextField(meetingNameField);
        styleTextField(hostField);
        styleTextField(cidField);
        styleTextField(userIdField);

        styleComboBox(meetingTypeCombo);
        styleComboBox(meetingFormCombo);
        styleComboBox(auditStatusCombo);
        styleComboBox(campusCombo);
        styleComboBox(locationCombo);
        styleComboBox(roomNumberCombo);

        startTimeSpinner.setEditor(new JSpinner.DateEditor(startTimeSpinner, "yyyy-MM-dd HH:mm:ss"));
        endTimeSpinner.setEditor(new JSpinner.DateEditor(endTimeSpinner, "yyyy-MM-dd HH:mm:ss"));
        styleSpinner(startTimeSpinner);
        styleSpinner(endTimeSpinner);

        // 统一标签样式
        Font labelFont = new Font("Microsoft YaHei", Font.BOLD, 14);
        Color labelColor = new Color(70, 70, 70);

        // 初始化地点数据
        initLocationData();

        // 布局所有组件
        int row = 0;



        // 会议ID
        JLabel meetingIdLabel = new JLabel("会议ID:");
        meetingIdLabel.setFont(labelFont);
        meetingIdLabel.setForeground(labelColor);
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.gridwidth = 1;
        add(meetingIdLabel, gbc);

        gbc.gridx = 1;
        add(meetingIdField, gbc);
        row++;

        // 会议名称
        JLabel meetingNameLabel = new JLabel("会议名称:");
        meetingNameLabel.setFont(labelFont);
        meetingNameLabel.setForeground(labelColor);
        gbc.gridx = 0;
        gbc.gridy = row;
        add(meetingNameLabel, gbc);

        gbc.gridx = 1;
        add(meetingNameField, gbc);
        row++;

        // 主持人
        JLabel hostLabel = new JLabel("主持人:");
        hostLabel.setFont(labelFont);
        hostLabel.setForeground(labelColor);
        addComponent(hostLabel, gbc, 0, row);
        addComponent(hostField, gbc, 1, row);
        row++;

        // 会议类型
        JLabel typeLabel = new JLabel("会议类型:");
        typeLabel.setFont(labelFont);
        typeLabel.setForeground(labelColor);
        addComponent(typeLabel, gbc, 0, row);
        addComponent(meetingTypeCombo, gbc, 1, row);
        row++;

        // 会议形式
        JLabel formLabel = new JLabel("会议形式:");
        formLabel.setFont(labelFont);
        formLabel.setForeground(labelColor);
        addComponent(formLabel, gbc, 0, row);
        addComponent(meetingFormCombo, gbc, 1, row);
        row++;

        // 开始时间
        JLabel startTimeLabel = new JLabel("开始时间:");
        startTimeLabel.setFont(labelFont);
        startTimeLabel.setForeground(labelColor);
        addComponent(startTimeLabel, gbc, 0, row);
        addComponent(startTimeSpinner, gbc, 1, row);
        row++;

        // 结束时间
        JLabel endTimeLabel = new JLabel("结束时间:");
        endTimeLabel.setFont(labelFont);
        endTimeLabel.setForeground(labelColor);
        addComponent(endTimeLabel, gbc, 0, row);
        addComponent(endTimeSpinner, gbc, 1, row);
        row++;

        // 会议CID
        JLabel cidLabel = new JLabel("会议CID:");
        cidLabel.setFont(labelFont);
        cidLabel.setForeground(labelColor);
        addComponent(cidLabel, gbc, 0, row);
        addComponent(cidField, gbc, 1, row);
        row++;

        // 用户ID
        JLabel userIdLabel = new JLabel("用户ID:");
        userIdLabel.setFont(labelFont);
        userIdLabel.setForeground(labelColor);
        addComponent(userIdLabel, gbc, 0, row);
        addComponent(userIdField, gbc, 1, row);
        row++;

        // 校区
        JLabel campusLabel = new JLabel("校区:");
        campusLabel.setFont(labelFont);
        campusLabel.setForeground(labelColor);
        addComponent(campusLabel, gbc, 0, row);
        addComponent(campusCombo, gbc, 1, row);
        row++;

        // 地点
        JLabel locationLabel = new JLabel("地点:");
        locationLabel.setFont(labelFont);
        locationLabel.setForeground(labelColor);
        addComponent(locationLabel, gbc, 0, row);
        addComponent(locationCombo, gbc, 1, row);
        row++;

        // 房间号
        JLabel roomLabel = new JLabel("房间号:");
        roomLabel.setFont(labelFont);
        roomLabel.setForeground(labelColor);
        addComponent(roomLabel, gbc, 0, row);
        addComponent(roomNumberCombo, gbc, 1, row);
        row++;

        // 审核状态
        JLabel statusLabel = new JLabel("审核状态:");
        statusLabel.setFont(labelFont);
        statusLabel.setForeground(labelColor);
        addComponent(statusLabel, gbc, 0, row);
        addComponent(auditStatusCombo, gbc, 1, row);
        row++;

        // 按钮面板布局
        JPanel buttonPanel = new JPanel(new GridBagLayout());
        buttonPanel.setOpaque(false);
        GridBagConstraints buttonGbc = new GridBagConstraints();
        buttonGbc.insets = new Insets(15, 0, 0, 0); // 增加上边距
        buttonGbc.gridwidth = 2;
        buttonGbc.anchor = GridBagConstraints.EAST;

        JButton confirmBtn = new JButton("确认预订");
        styleButton(confirmBtn, new Color(76, 175, 80));
        confirmBtn.addActionListener(this::confirmAction);

        JButton cancelBtn = new JButton("取消");
        styleButton(cancelBtn, new Color(244, 67, 54));
        cancelBtn.addActionListener(e -> dispose());

        buttonPanel.add(confirmBtn, buttonGbc);
        buttonGbc.gridy = 1; // 将取消按钮放在第二行
        buttonPanel.add(cancelBtn, buttonGbc);

        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.NONE; // 重要：确保不填充额外空间
        gbc.anchor = GridBagConstraints.CENTER;
        gbc.insets = new Insets(20, 0, 10, 0);

        buttonPanel.add(confirmBtn);
        buttonPanel.add(cancelBtn);

        add(buttonPanel, gbc);

        // 确保对话框尺寸合适
        pack();
        setMinimumSize(new Dimension(400, 600)); // 设置最小尺寸
        setLocationRelativeTo(getOwner());
    }

    private void initLocationData() {
        Map<String, List<String>> lingangLocations = new HashMap<>();
        lingangLocations.put("学术楼", Arrays.asList("101", "102", "103", "106", "201", "202", "203", "204", "205", "301", "302", "303"));
        lingangLocations.put("红楼", Arrays.asList("107"));
        lingangLocations.put("经外楼", Arrays.asList("201", "301", "401", "501"));
        lingangLocations.put("1号教学楼", Arrays.asList("101", "102", "103", "106", "201", "202", "203", "204", "205", "206", "301", "302", "303", "406"));

        Map<String, List<String>> yangpuLocations = new HashMap<>();
        yangpuLocations.put("杨浦会议厅", Arrays.asList("101", "201", "301", "401", "501"));
        yangpuLocations.put("杨浦报告厅", Arrays.asList("101", "201", "301", "401", "501"));

        campusCombo.addActionListener(e -> {
            String selectedCampus = (String) campusCombo.getSelectedItem();
            locationCombo.removeAllItems();
            roomNumberCombo.removeAllItems();

            if ("临港".equals(selectedCampus)) {
                lingangLocations.keySet().forEach(locationCombo::addItem);
            } else if ("杨浦".equals(selectedCampus)) {
                yangpuLocations.keySet().forEach(locationCombo::addItem);
            }
        });

        locationCombo.addActionListener(e -> {
            String selectedCampus = (String) campusCombo.getSelectedItem();
            String selectedLocation = (String) locationCombo.getSelectedItem();
            roomNumberCombo.removeAllItems();

            if ("临港".equals(selectedCampus)) {
                lingangLocations.get(selectedLocation).forEach(roomNumberCombo::addItem);
            } else if ("杨浦".equals(selectedCampus)) {
                yangpuLocations.get(selectedLocation).forEach(roomNumberCombo::addItem);
            }
        });
    }

    private void addComponent(Component comp, GridBagConstraints gbc, int x, int y) {
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = 1;
        add(comp, gbc);
    }

    // 统一样式方法
    private void styleTextField(JTextField textField) {
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(180, 180, 190)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));
    }

    private void styleComboBox(JComboBox<?> comboBox) {
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        comboBox.setBackground(Color.WHITE);
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(180, 180, 190)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));
    }

    private void styleSpinner(JSpinner spinner) {
        spinner.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor)spinner.getEditor();
        editor.getTextField().setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(180, 180, 190)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));
    }

    private void styleButton(JButton button, Color bgColor) {
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(bgColor.darker(), 1),
                BorderFactory.createEmptyBorder(5, 15, 5, 15)
        ));
        button.setFocusPainted(false);
        button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }

    // 确认按钮事件处理
    private void confirmAction(ActionEvent e) {
        try {
            if (!validateForm()) return;

            Meeting meeting = createMeetingFromForm();

            // 检查用户和会议是否存在
            if (!meetingService1.checkUserExists(meeting.getID())) {
                throw new SQLException("用户ID不存在");
            }
            if (!meetingService1.checkConferenceExists(meeting.getCID())) {
                throw new SQLException("会议CID不存在");
            }

            // 保存到数据库
            if (meetingService1.addMeeting(meeting)) {
                JOptionPane.showMessageDialog(this,
                        "会议预订成功！\n会议ID: " + meeting.getMID(),
                        "成功",
                        JOptionPane.INFORMATION_MESSAGE);

                // 立即关闭对话框并触发刷新
                dispose();
            } else {
                JOptionPane.showMessageDialog(this,
                        "会议保存失败，请重试！",
                        "错误",
                        JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this,
                    "发生错误: " + ex.getMessage(),
                    "错误",
                    JOptionPane.ERROR_MESSAGE);
            ex.printStackTrace();
        }
    }

    private boolean validateForm() {
        // 检查必填字段
        if (meetingIdField.getText().trim().isEmpty()) {
            showError("会议ID不能为空");
            return false;
        }
        if (meetingNameField.getText().trim().isEmpty()) {
            showError("会议名称不能为空");
            return false;
        }
        if (hostField.getText().trim().isEmpty()) {
            showError("主持人不能为空");
            return false;
        }
        if (userIdField.getText().trim().isEmpty()) {
            showError("用户ID不能为空");
            return false;
        }

        // 检查时间
        Date startTime = (Date) startTimeSpinner.getValue();
        Date endTime = (Date) endTimeSpinner.getValue();

        if (startTime == null || endTime == null) {
            showError("请选择有效的时间");
            return false;
        }

        if (startTime.before(new Date())) {
            showError("开始时间不能早于当前时间");
            return false;
        }

        if (endTime.before(startTime)) {
            showError("结束时间不能早于开始时间");
            return false;
        }

        // 检查会议室选择
        if (roomNumberCombo.getSelectedItem() == null) {
            showError("请选择会议室");
            return false;
        }

        return true;
    }

    // createMeetingFromForm 方法
    private Meeting createMeetingFromForm() {
        Meeting meeting = new Meeting();
        meeting.setMID(meetingIdField.getText().trim());
        meeting.setMname(meetingNameField.getText().trim());
        meeting.setName(hostField.getText().trim());

        // 正确的 Timestamp 转换方式
        Date startTime = (Date) startTimeSpinner.getValue();
        meeting.setMstarttime(new Timestamp(startTime.getTime()));

        Date endTime = (Date) endTimeSpinner.getValue();
        meeting.setMendtime(new Timestamp(endTime.getTime()));

        meeting.setPlace((String) campusCombo.getSelectedItem());
        meeting.setLocation((String) locationCombo.getSelectedItem());
        meeting.setRoom((String) roomNumberCombo.getSelectedItem());
        meeting.setForm((String) meetingFormCombo.getSelectedItem());
        meeting.setType((String) meetingTypeCombo.getSelectedItem());
        meeting.setStatus((String) auditStatusCombo.getSelectedItem());
        meeting.setCID(cidField.getText().trim());
        meeting.setID(userIdField.getText().trim());
        return meeting;
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(
                this,
                message,
                "输入错误",
                JOptionPane.ERROR_MESSAGE
        );
    }

    private void addComponent(Component component, GridBagConstraints gbc, int gridx, int gridy, int gridwidth, int gridheight) {
        gbc.gridx = gridx;
        gbc.gridy = gridy;
        gbc.gridwidth = gridwidth;
        gbc.gridheight = gridheight;
        add(component, gbc);
    }

    private boolean validateForm(JTextField meetingIdField, JTextField meetingNameField,
                                 JTextField hostField, JSpinner startTimeSpinner, JSpinner endTimeSpinner) {
        if (meetingIdField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "会议ID不能为空");
            return false;
        }
        if (meetingNameField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "会议名称不能为空");
            return false;
        }
        if (hostField.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "主持人不能为空");
            return false;
        }

        Date startTime = (Date) startTimeSpinner.getValue();
        Date endTime = (Date) endTimeSpinner.getValue();

        if (startTime.before(new Date())) {
            JOptionPane.showMessageDialog(this, "开始时间不能早于当前时间");
            return false;
        }

        if (endTime.before(startTime)) {
            JOptionPane.showMessageDialog(this, "结束时间不能早于开始时间");
            return false;
        }

        return true;
    }
}

class MeetingService1 {
    private final MeetingDao meetingDAO = new MeetingDao();

    public boolean testConnection() {
        return meetingDAO.testConnection();
    }
    // 检查CID是否存在的方法
    public boolean checkConferenceExists(String cid) {
        return meetingDAO.checkConferenceExists(cid);
    }
    // 检查用户是否存在的方法
    public boolean checkUserExists(String userId) {
        return meetingDAO.checkUserExists(userId);
    }
    public boolean addMeeting(Meeting meeting) throws Exception {
        try {
            if (checkMeetingIdExists(meeting.getMID())) {
                throw new Exception("会议ID已存在: " + meeting.getMID());
            }

            // 检查CID是否存在
            if (meeting.getCID() != null && !meeting.getCID().isEmpty() &&
                    !checkConferenceExists(meeting.getCID())) {
                throw new SQLException("会议CID不存在: " + meeting.getCID());}

            // 添加额外验证
            if (meeting.getPlace() == null || (!meeting.getPlace().equals("临港") && !meeting.getPlace().equals("杨浦"))) {
                throw new SQLException("校区(place)必须是'临港'或'杨浦'");
            }

            if (meeting.getRoom() == null || !meeting.getRoom().matches("\\d{3}")) {
                throw new SQLException("房间号(room)必须是3位数字");
            }

            return meetingDAO.addMeeting(meeting);
        } catch (SQLException e) {
            throw new Exception("数据库操作失败", e);
        }
    }

    public List<Meeting> getAllMeetings() {
        return meetingDAO.getAllMeetings();
    }

    public boolean checkMeetingIdExists(String meetingId) {
        return meetingDAO.checkMeetingIdExists(meetingId);
    }
}


class ReservationConflictException extends Exception {
    public ReservationConflictException(String message) {
        super(message);
    }
}

